package service;

import JDBC.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
/**
 * @author Gao Shiwei
 * the function of this class is adding new items
 */
public class AddNewItem extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
            String ItemName=req.getParameter("ItemName");

            String ItemPrice=req.getParameter("ItemPrice");

            String ItemType=req.getParameter("ItemType");

            String ItemDescription=req.getParameter("ItemDescription");

            String ItemQuantity=req.getParameter("ItemQuantity");

            //this part can get the concrete time

        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int curHour24=cal.get(Calendar.HOUR_OF_DAY);
        int minute=cal.get(Calendar.MINUTE);
        int miao=cal.get(Calendar.SECOND);



        String ItemID=String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(curHour24)+String.valueOf(minute)+String.format("%02d",miao);
    try {
        DBUtils.addItem(ItemID, ItemName, Double.parseDouble(ItemPrice), ItemType, ItemDescription, Integer.parseInt(ItemQuantity));
        HttpSession session = req.getSession();
        String PhoneNumber = (String) session.getAttribute("PhoneNumber");
        DBUtils.addReleaseInformation(PhoneNumber, ItemID, Integer.parseInt(ItemQuantity));


        PrintWriter out = resp.getWriter();
        String str = "{\"ItemID\":\"" + ItemID + "\"}";
        out.println(str);
        out.flush();
        out.close();
    }catch(Exception e){
        PrintWriter out = resp.getWriter();
        String str = "{\"ItemID\":\"" + "false" + "\"}";
        out.println(str);
        out.flush();
        out.close();
    }
    }

}
